package com.blog.effective.note3;

import java.lang.reflect.Constructor;

/**
 * @func 用私有构造器或者枚举类型强化Singleton属性.
 * @author 张俊强~
 * @time 2017/10/30 21:00
 */
public class EffectiveJavaDemoOne {

    public static void main(String[] args) throws Exception {
        UserInfo userInfo=UserInfo.userInfo;
        System.out.println(userInfo);

        // 第利用反射机制调用私有构造函数
        Class<?> class1 = Class.forName("com.UserInfo");
        // 得到全部的构造函数
        Constructor con = class1.getDeclaredConstructor();
        con.setAccessible(true);
//        UserInfo userInfo1=(UserInfo) con.newInstance();//再次创建一个实例

        StudentInfo studentInfo=StudentInfo.STUDENT_INFO;
        studentInfo.setStudentName("暂时");
        System.out.println(studentInfo.getStudentName());
    }

}

class UserInfo{
    public static final UserInfo userInfo = new UserInfo();
    private UserInfo(){
        // 用户通过反射机制再次创建实例，则抛异常（先不用理解，后面有说到）
        if(UserInfo.userInfo!=null){
            throw new RuntimeException("不能创建多个对象");
        }
    }
}

enum StudentInfo{
    STUDENT_INFO;
    private String studentName;
    private String studentSex;
    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public String getStudentSex() {
        return studentSex;
    }

    public void setStudentSex(String studentSex) {
        this.studentSex = studentSex;
    }
}
